package com.baidu.process.chat.parser.sourceHandler.impl;

import com.alibaba.fastjson.JSONObject;
import com.baidu.process.chat.core.web.bean.IMRequestServer;
import com.baidu.process.chat.core.web.bean.eval.EvalResult;
import com.baidu.process.chat.core.web.bean.eval.EvalVO;
import com.baidu.process.chat.core.web.service.IEvaluationService;
import com.baidu.process.chat.parser.bean.QueryJsonStr;
import com.baidu.process.chat.parser.sourceHandler.BaseSourceHandler;
import com.baidu.process.constant.EvalConstant;
import com.baidu.process.constant.RedisKey;
import com.baidu.process.imchat.entity.ImResult;
import com.baidu.process.imchat.service.ImChatService;
import com.baidu.process.ngd.bean.NGDResBody;
import com.baidu.process.record.bean.DialogueRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.baidu.process.constant.RedisKey.*;

/**
 * @Author:fangyuchao
 * @Description: 多轮对话处理期
 * @Date: Create in 11:35 2022/11/8
 */
@Service
public class TaskBaseHandler implements BaseSourceHandler {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Value("#{'${ngd.filter.answerActions}'.split(',')}")
    private List<String> answerActions;
    @Autowired
    private IEvaluationService evalResultService;
    @Autowired
    private ImChatService imChatService;
    @Override
    public QueryJsonStr handleQuery(NGDResBody ngdResBody, IMRequestServer imRequestServer, DialogueRecord dialogueRecord) {
        //给im发送的信息列表
        List<String> imMsgList = new ArrayList<>();
        String channel = imRequestServer.getChannel();
        QueryJsonStr queryJsonStr = new QueryJsonStr();
        NGDResBody.NGDQueryData  queryData = ngdResBody.getData();
        String sessionId = queryData.getSessionId();
        Map<String,Object> debug = queryData.getDebug();
        Object detailObj = debug.get("detail");
        Map<String,Object> detail = JSONObject.parseObject(JSONObject.toJSONString(detailObj),Map.class);
        Object nluObj = detail.get("nlu");
        Map<String,Object> nlu = JSONObject.parseObject(JSONObject.toJSONString(nluObj),Map.class);
        Object intentsObj = nlu.get("intents");
        String nameZh;
        if(StringUtils.isEmpty(intentsObj)){
            //空的就取redis内的值
            nameZh = redisTemplate.opsForValue().get(IntentKey+sessionId);
        }else{
            Map<String,Object> intents = JSONObject.parseObject(JSONObject.toJSONString(intentsObj),Map.class);
            Object nameZhObj = intents.get("nameZh");

            if (StringUtils.isEmpty(nameZhObj)){
                //空的就取redis内的值
                nameZh = redisTemplate.opsForValue().get(IntentKey+sessionId);
            }else{
                nameZh = nameZhObj.toString();
                //有新意图就存入redis
                redisTemplate.opsForValue().set(IntentKey+sessionId,nameZh,10, TimeUnit.HOURS);
            }

        }
        dialogueRecord.setIntentName(nameZh);
        //获取回复文本
        Map<String,Object> answer = queryData.getAnswer();

        String answerText = answer.get("answerText").toString();
        Map<String,Object> context = queryData.getContext();
        String car_distributor = StringUtils.isEmpty(context.get("car_distributor"))?"":context.get("car_distributor").toString();
        dialogueRecord.setCar_distributor(car_distributor);
        //重置澄清次数
        redisTemplate.opsForValue().set(ClarfyKey+sessionId,"0");
        queryJsonStr.setSessionId(queryData.getSessionId());
        queryJsonStr.setSource(queryData.getSource());
        queryJsonStr.setAnswer(excptAtion(answerText));
        queryJsonStr.setContext(queryData.getContext());
        String action = actionExract(answerText);
        queryJsonStr.setBot(action);
        switch (action){
            //4为系统挂机，不再推送满意度
            case "4":
                queryJsonStr.setBot("1");
                redisTemplate.delete(ImSilentNumKey+sessionId);
                redisTemplate.delete(ImTimeKey+sessionId);
            break;
            case "1":
                //action是1，挂机的情况下推送满意度链接
                List<Map<String,Object>> msgBody = new ArrayList<>();
                Map<String,Object> map = new HashMap<>();
                map.put("msgType","TIMTextElem");
                Map<String,String> textMap = new HashMap<>();
                //调用满意度接口获取满意度链接
                EvalVO evalVO = new EvalVO();
                evalVO.setChannel(channel);
                evalVO.setSessionId(sessionId);
                EvalResult evalResult = evalResultService.pushEval(evalVO);
                //通过渠道推送不同链接格式
                //渠道0推送
                if (EvalConstant.CHANNEL_WX.equals(channel)){
                    map.put("msgType","TIMTextElem");
                    String evalUrl = JSONObject.parseObject(evalResult.getJsonString()).get("url").toString();
                    //拼接上满意度
                    textMap.put("text","<a href='"+evalUrl+"'>客户满意度调研</a>");
                }else{
                    map.put("msgType","TIMCustomElem");
                    String evalJson = evalResult.getJsonString();
                    //推送满意度
                    textMap.put("desc",evalJson);
                }
                map.put("msgContent",textMap);
                msgBody.add(map);
                ImResult imResult = imChatService.imChat(imRequestServer,msgBody);
                imMsgList.add(JSONObject.toJSONString(msgBody));
                //发完满意度后再提交关闭
                List<Map<String,Object>> closeMsgBody = new ArrayList<>();
                Map<String,Object> closeMap = new HashMap<>();
                Map<String,String> closeTextMap = new HashMap<>();
                closeTextMap.put("text",excptAtion(answerText));
                closeMap.put("msgContent",closeTextMap);
                closeMap.put("msgType","TIMClose");
                closeMsgBody.add(closeMap);
                ImResult imCloseResult = imChatService.imChat(imRequestServer,closeMsgBody);
                imMsgList.add(JSONObject.toJSONString(closeMsgBody));
                redisTemplate.delete(ImSilentNumKey+sessionId);
                redisTemplate.delete(ImTimeKey+sessionId);
                break;
                //转人工不再推送静默
            case "2":
                redisTemplate.delete(ImSilentNumKey+sessionId);
                redisTemplate.delete(ImTimeKey+sessionId);
                break;
            default:
        }
        dialogueRecord.setImchatData(JSONObject.toJSONString(imMsgList));
        return queryJsonStr;
    }

    /**
     * 去除话术内的@@指令
     * @param answerText
     * @return
     */
    private String excptAtion(String answerText){
        String resultAnwer = answerText;
        for (String action :answerActions){
            resultAnwer = resultAnwer.replace(action,"");
        }
        return  resultAnwer;
    }


    //提取话术内的指令,去除@@符号
    private String actionExract(String suggestAnswer){
        //默认正常回复
        String action = "0";
        for (String action_1 : answerActions){
            if (suggestAnswer.contains(action_1)){
                action=action_1.replace("@","");
                break;
            }
        }
        return action;
    }
}
